package model

import (
	"context"

	"github.com/Masterminds/squirrel"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var _ AwJobsModel = (*customAwJobsModel)(nil)

type (
	// AwJobsModel is an interface to be customized, add more methods here,
	// and implement the added methods in customAwJobsModel.
	AwJobsModel interface {
		awJobsModel
		withSession(session sqlx.Session) AwJobsModel
		ListByCondition(ctx context.Context, session sqlx.Session, pagenum, pagesize int64, cateIds, cityIds []*int64,keyWord string) ([]*AwJobsExpand, error)
		GetCount(ctx context.Context,session sqlx.Session,keyword string,cateIds,cityIds []*int64) (int64, error)
	}

	customAwJobsModel struct {
		*defaultAwJobsModel
	}
)

// NewAwJobsModel returns a model for the database table.
func NewAwJobsModel(conn sqlx.SqlConn) AwJobsModel {
	return &customAwJobsModel{
		defaultAwJobsModel: newAwJobsModel(conn),
	}
}

func (m *customAwJobsModel) withSession(session sqlx.Session) AwJobsModel {
	return NewAwJobsModel(sqlx.NewSqlConnFromSession(session))
}

func (m *customAwJobsModel) ListByCondition(ctx context.Context, session sqlx.Session, pagenum, pagesize int64, cateIds, cityIds []*int64,keyWord string) ([]*AwJobsExpand, error) {
	sb := squirrel.Select("`aw_jobs`.*,jc.name as catename,ci.name as cityname").From(m.table)
	if cateIds != nil{
		if len(cateIds) > 0 {
			sb = sb.Where(squirrel.Eq{"job_category":cateIds})
		}
	}
	if cityIds != nil{
		if len(cityIds) > 0 {
			sb = sb.Where(squirrel.Eq{"city":cityIds})
		}
	}
	if len(keyWord) > 0 {
		sb = sb.Where(squirrel.Like{"title":"%"+keyWord+"%"})
	}
	sb = sb.InnerJoin("`aw_job_categories` jc on jc.id = `aw_jobs`.job_category")
	sb = sb.InnerJoin("`aw_city_infos` ci on ci.id = `aw_jobs`.city")
	sb = sb.Offset(uint64((pagenum - 1) * (pagesize))).Limit(uint64(pagesize))
	query, args, err := sb.ToSql()

	if err != nil {
		return nil, err
	}

	var jobs []*AwJobsExpand
	if session != nil {
		err = session.QueryRowsPartialCtx(ctx, &jobs, query, args...)
	} else {
		err = m.conn.QueryRowsPartialCtx(ctx, &jobs, query, args...)
	}

	return jobs, err
	// .Where("city in (?)",strings.Join(cateIds,","))
}

func (m *customAwJobsModel) GetCount(ctx context.Context,session sqlx.Session,keyword string,cateIds,cityIds []*int64) (int64, error) {
	sb := squirrel.Select("count(1)").From(m.table)
	if cateIds != nil{
		if len(cateIds) > 0 {
			sb = sb.Where(squirrel.Eq{"job_category":cateIds})
		}
	}
	if cityIds != nil{
		if len(cityIds) > 0 {
			sb = sb.Where(squirrel.Eq{"city":cityIds})
		}
	}
	if len(keyword) > 0 {
		sb = sb.Where(squirrel.Like{"title":"%"+keyword+"%"})
	}
	toSql, args, err := sb.ToSql()
	if err != nil {
		return 0, err
	}
	var count int64
	err = m.conn.QueryRowCtx(ctx, &count, toSql, args...)
	switch err {
	case nil:
		return count, nil
	default:
		return 0, err
	}
}
